<template>
  <div class="login-register-overlay" v-if="visible" :class="{ 'slide-in': visible, 'slide-out': isExiting }"
    @transitionend="handleTransitionEnd">
    <div class="login-module" v-if="showLoginModule"
      :style="{ transform: `translateY(${showLoginModule ? '0' : '100%'})` }">
      <div class="close" @click="hideLogin">
        <van-icon name="arrow-left" />
      </div>
      <div class="login-img">
        <img src="../assets/login-img.png" alt="">
      </div>
      <div class="login-title">
        <span>{{ isPasswordLogin ? '密码登录' : '手机号验证码登录' }}</span>
        <span v-show="!isPasswordLogin">短信验证后自动登录</span>
      </div>

      <div class="login-input">
        <div class="phone-number">
          <i class="login-iconfont icon-phoneNumber"></i>
          <input type="text" placeholder="手机号码" v-model="phoneNumber" @input="handlePhoneInput">
        </div>
        <div class="verification-code">
          <i class="login-iconfont" :class="isPasswordLogin ? 'icon-password' : 'icon-yzm'"></i>
          <div class="error-tip" v-if="codeErrorTip">{{ codeErrorTip }}</div>
          <input :type="isPasswordLogin ? (showPassword ? 'text' : 'password') : 'text'"
            :placeholder="isPasswordLogin ? '请输入密码' : '短信验证码'" v-model="verificationCode" @input="handleCodeInput">
          <div class="send-code" :class="{ 'disabled': isCodeCountdowning }" v-show="!isPasswordLogin"
            @click="sendVerificationCode('login')">{{ codeCountdown > 0 ? `${codeCountdown}秒` : '发送验证码' }}</div>
          <i v-if="isPasswordLogin" class="show-password login-iconfont"
            :class="showPassword ? 'icon-show' : 'icon-hide'" @click="togglePasswordVisibility"></i>
        </div>
      </div>

      <div class="agreement-module">
        <div class="circle" :class="{ active: agreementActive }" @click="toggleAgreement">✓</div>
        我已阅读并同意
        <span>《用户服务协议》</span>
        和
        <span>《隐私政策》</span>
      </div>

      <button class="login-btn" :style="{ backgroundColor: canLogin ? '#000' : '#ccc' }" :disabled="!canLogin"
        @click="login">登录</button>
      <div class="login-options">
        <span class="password-login" @click="toggleLoginType">{{ isPasswordLogin ? '验证码登录' : '密码登录' }}</span>
        <span class="register" @click="showRegisterModule">注册</span>
      </div>



    </div>

    <div class="register-module" v-if="isRegisterModuleVisible"
      :style="{ transform: `translateY(${isRegisterModuleVisible ? '0' : '100%'})` }">
      <div class="close" @click="hideRegister">
        <van-icon name="arrow-left" />
      </div>
      <div class="register-img">
        <img src="../assets/login-img.png" alt="">
      </div>
      <div class="register-title">
        <span>注册账号</span>
        <span>短信验证后自动登录</span>
      </div>

      <div class="register-input">
        <div class="phone-number">
          <i class="login-iconfont icon-phoneNumber"></i>
          <input type="text" placeholder="手机号码" v-model="registerPhone" @input="handleRegisterPhoneInput">
        </div>

        <div class="verification-code">
          <i class="login-iconfont icon-yzm"></i>
          <input type="text" placeholder="短信验证码" v-model="registerCode" @input="handleRegisterCodeInput">
          <div class="send-code" :class="{ 'disabled': isRegisterCodeCountdowning }"
            @click="sendVerificationCode('register')">{{ registerCodeCountdown > 0 ? `${registerCodeCountdown}秒` :
              '发送验证码' }}</div>
        </div>
        <div class="password-input">
          <i class="login-iconfont icon-password"></i>
          <input :type="showRegisterPassword ? 'text' : 'password'" placeholder="设置密码" v-model="registerPassword"
            @input="handleRegisterPasswordInput">
          <i class="show-password login-iconfont" :class="showRegisterPassword ? 'icon-show' : 'icon-hide'"
            @click="toggleRegisterPasswordVisibility"></i>
        </div>
      </div>

      <div class="agreement-module">
        <div class="circle" :class="{ active: agreementActive }" @click="toggleAgreement">✓</div>
        我已阅读并同意
        <span>《用户服务协议》</span>
        和
        <span>《隐私政策》</span>
      </div>

      <button class="register-btn" :style="{ backgroundColor: canRegister ? '#000' : '#ccc' }" :disabled="!canRegister"
        @click="register">注册</button>

    </div>

    <van-dialog v-model="showPasswordDialog" title="您是新用户，请设置您的账号密码" :show-confirm-button="true"
      :show-cancel-button="false" confirm-button-text="确认" @confirm="confirmPassword">
      <div class="password-dialog-content">
        <div class="password-input-wrapper">
          <input :type="showDialogPassword ? 'text' : 'password'" v-model="dialogPassword" placeholder="请输入密码（至少6位）"
            class="password-dialog-input" />
          <i class="login-iconfont" :class="showDialogPassword ? 'icon-show' : 'icon-hide'"
            @click="toggleDialogPassword"></i>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import { Icon } from 'vant';

export default {
  name: 'LoginRegister',
  components: {
    [Icon.name]: Icon
  },
  data() {
    return {
      visible: false, // 控制登录注册组件是否可见
      isExiting: false, // 控制组件退出动画
      isPasswordLogin: false, // 是否为密码登录模式
      showPassword: false, // 是否显示密码（登录模块）
      agreementActive: false, // 是否勾选协议
      phoneNumber: '', // 登录手机号
      verificationCode: '', // 验证码或密码（登录模块）
      showLoginModule: false, // 是否显示登录模块
      isRegisterModuleVisible: false, // 是否显示注册模块
      registerPhone: '', // 注册手机号
      registerCode: '', // 注册验证码
      registerPassword: '', // 注册密码
      showRegisterPassword: false, // 是否显示注册密码
      codeCountdown: 0, // 登录验证码倒计时
      isCodeCountdowning: false, // 登录验证码是否正在倒计时
      registerCodeCountdown: 0, // 注册验证码倒计时
      isRegisterCodeCountdowning: false, // 注册验证码是否正在倒计时
      codeErrorTip: '', // 验证码错误提示
      showPasswordDialog: false, // 是否显示密码设置对话框
      dialogPassword: '', // 对话框中的密码
      showDialogPassword: false, // 是否显示对话框密码
      passwordDialogResolve: null, // 密码对话框Promise的resolve函数
      currentRoutePath: '' // 记录打开登录组件时的路由路径
    }
  },
  computed: {
    ...mapState({
      storeVerificationCode: 'verificationCode' // 从store中获取验证码
    }),
    isPhoneValid() {
      // 验证登录手机号格式是否正确
      const phoneRegex = /^1\d{10}$/;
      return phoneRegex.test(this.phoneNumber.trim());
    },
    isCodeValid() {
      // 验证登录验证码或密码是否已输入
      return this.verificationCode.trim() !== '';
    },
    canLogin() {
      // 判断是否可以登录（需勾选协议、手机号有效、验证码已输入）
      return this.agreementActive && this.isPhoneValid && this.isCodeValid;
    },
    isRegisterPhoneValid() {
      // 验证注册手机号格式是否正确
      const phoneRegex = /^1\d{10}$/;
      return phoneRegex.test(this.registerPhone.trim());
    },
    isRegisterCodeValid() {
      // 验证注册验证码是否已输入
      return this.registerCode.trim() !== '';
    },
    isRegisterPasswordValid() {
      // 验证注册密码长度是否至少6位
      return this.registerPassword.trim().length >= 6;
    },
    canRegister() {
      // 判断是否可以注册（需勾选协议、手机号有效、验证码已输入、密码有效）
      return this.agreementActive && this.isRegisterPhoneValid && this.isRegisterCodeValid && this.isRegisterPasswordValid;
    }
  },
  created() {
    // 监听全局事件，显示登录组件
    this.$root.$on('showLoginRegister', (routePath) => {
      this.currentRoutePath = routePath || this.$route.path;
      this.show();
    });
  },
  beforeDestroy() {
    // 移除全局事件监听
    this.$root.$off('showLoginRegister');
  },
  methods: {
    ...mapMutations(['SET_VERIFICATION_CODE', 'CLEAR_VERIFICATION_CODE']),

    // 显示登录注册组件
    show() {
      this.visible = true;
      this.isExiting = false;
      this.showLoginModule = true;
      this.isRegisterModuleVisible = false;
      // 重置表单
      this.resetForm();
    },

    // 隐藏登录注册组件
    hide() {
      this.isExiting = true;
    },

    // 处理过渡动画结束事件
    handleTransitionEnd() {
      if (this.isExiting) {
        this.visible = false;
        this.isExiting = false;
        this.showLoginModule = false;
        this.isRegisterModuleVisible = false;
      }
    },

    // 重置表单数据
    resetForm() {
      this.phoneNumber = '';
      this.verificationCode = '';
      this.registerPhone = '';
      this.registerCode = '';
      this.registerPassword = '';
      this.agreementActive = false;
      this.codeErrorTip = '';
      this.isPasswordLogin = false;
    },

    // 发送验证码
    sendVerificationCode(type) {
      // 检查是否勾选协议
      if (!this.agreementActive) {
        this.$toast({
          message: '请先阅读并同意相关协议',
          position: 'top',
        });
        return;
      }

      const phoneValid = type === 'login' ? this.isPhoneValid : this.isRegisterPhoneValid;

      if (!phoneValid) {
        this.$toast({
          message: '请输入正确的手机号码',
          position: 'top',
        });
        return;
      }

      const code = Math.floor(100000 + Math.random() * 900000).toString();
      this.SET_VERIFICATION_CODE(code);

      this.$toast({
        message: `验证码：${code}`,
        position: 'top',
        duration: 10000,
      });

      if (type === 'login') {
        this.isCodeCountdowning = true;
        this.codeCountdown = 60;
        const timer = setInterval(() => {
          this.codeCountdown--;
          if (this.codeCountdown <= 0) {
            clearInterval(timer);
            this.isCodeCountdowning = false;
          }
        }, 1000);
      } else {
        this.isRegisterCodeCountdowning = true;
        this.registerCodeCountdown = 60;
        const timer = setInterval(() => {
          this.registerCodeCountdown--;
          if (this.registerCodeCountdown <= 0) {
            clearInterval(timer);
            this.isRegisterCodeCountdowning = false;
          }
        }, 1000);
      }
    },

    // 切换登录类型（验证码登录/密码登录）
    toggleLoginType() {
      this.isPasswordLogin = !this.isPasswordLogin;
      this.codeErrorTip = '';
    },

    // 切换密码显示/隐藏（登录模块）
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },

    // 切换协议勾选状态
    toggleAgreement() {
      this.agreementActive = !this.agreementActive;
    },

    // 验证登录输入
    validateInput() {
      if (this.agreementActive && !this.isPhoneValid && this.isCodeValid) {
        this.$toast({
          message: '账号或密码错误',
          position: 'top',
        });
      }
    },

    // 显示登录模块
    showLogin() {
      if (!this.agreementActive) {
        this.$toast({
          message: '登录/注册前请先阅读并同意相关协议',
          position: 'top',
        });
        return;
      }
      this.showLoginModule = true;
    },

    // 隐藏登录模块
    hideLogin() {
      this.hide();
    },

    // 显示注册模块
    showRegisterModule() {
      if (!this.agreementActive) {
        this.$toast({
          message: '登录/注册前请先阅读并同意相关协议',
          position: 'top',
        });
        return;
      }
      this.isRegisterModuleVisible = true;
      this.showLoginModule = false;
    },

    // 隐藏注册模块
    hideRegister() {
      this.isRegisterModuleVisible = false;
      this.showLoginModule = true;
    },

    // 切换注册密码显示/隐藏
    toggleRegisterPasswordVisibility() {
      this.showRegisterPassword = !this.showRegisterPassword;
    },

    // 处理登录手机号输入
    handlePhoneInput() {
      this.$nextTick(() => {
        this.validateInput();
      });
    },

    // 处理登录验证码输入
    handleCodeInput() {
      this.$nextTick(() => {
        this.validateInput();
      });
    },

    // 处理注册手机号输入
    handleRegisterPhoneInput() {
      this.$nextTick(() => {
        this.validateRegisterInput();
      });
    },

    // 处理注册验证码输入
    handleRegisterCodeInput() {
      this.$nextTick(() => {
        this.validateRegisterInput();
      });
    },

    // 处理注册密码输入
    handleRegisterPasswordInput() {
      this.$nextTick(() => {
        this.validateRegisterInput();
      });
    },

    // 验证注册输入
    validateRegisterInput() {
      if (this.agreementActive && !this.isRegisterPhoneValid && this.isRegisterCodeValid) {
        this.$toast({
          message: '手机号格式不正确',
          position: 'top',
        });
      }
    },

    // 执行登录操作
    async login() {
      if (!this.canLogin) return;

      if (this.isPasswordLogin) {
        const users = JSON.parse(localStorage.getItem('users') || '[]');
        const user = users.find(u => u.phoneNumber === this.phoneNumber);

        if (user && user.password === this.verificationCode) {
          localStorage.setItem('isLoggedIn', 'true');
          localStorage.setItem('currentPhoneNumber', this.phoneNumber);
          this.$toast({
            message: '登录成功',
            position: 'top',
          });
          this.hide();
          this.handleLoginSuccess();
        } else {
          this.$toast({
            message: '账号或密码错误',
            position: 'top',
          });
        }
        return;
      }

      this.codeErrorTip = '';

      if (this.verificationCode !== this.storeVerificationCode) {
        this.codeErrorTip = '验证码错误';
        return;
      }

      const users = JSON.parse(localStorage.getItem('users') || '[]');
      const user = users.find(u => u.phoneNumber === this.phoneNumber);

      if (user) {
        localStorage.setItem('isLoggedIn', 'true');
        localStorage.setItem('currentPhoneNumber', this.phoneNumber);
        this.$toast({
          message: '登录成功',
          position: 'top',
        });
        this.hide();
        this.CLEAR_VERIFICATION_CODE();
        this.handleLoginSuccess();
      } else {
        const password = await this.openPasswordDialog();
        if (!password) return;

        const defaultNickname = this.getDefaultNickname(this.phoneNumber);
        const newUser = {
          phoneNumber: this.phoneNumber,
          password: password,
          nickname: defaultNickname
        };
        users.push(newUser);
        localStorage.setItem('users', JSON.stringify(users));

        localStorage.setItem('isLoggedIn', 'true');
        localStorage.setItem('currentPhoneNumber', this.phoneNumber);
        this.$toast({
          message: '注册并登录成功',
          position: 'top',
        });
        this.hide();
        this.CLEAR_VERIFICATION_CODE();
        this.handleLoginSuccess();
      }
    },

    // 打开密码设置对话框
    openPasswordDialog() {
      return new Promise((resolve) => {
        this.dialogPassword = '';
        this.showDialogPassword = false;
        this.passwordDialogResolve = resolve;
        this.showPasswordDialog = true;
      });
    },

    // 切换对话框密码显示/隐藏
    toggleDialogPassword() {
      this.showDialogPassword = !this.showDialogPassword;
    },

    // 确认密码设置
    confirmPassword() {
      if (this.dialogPassword.trim().length < 6) {
        this.$toast({
          message: '密码长度至少6位',
          position: 'top',
        });
        return;
      }

      if (this.passwordDialogResolve) {
        this.passwordDialogResolve(this.dialogPassword.trim());
        this.passwordDialogResolve = null;
      }
      this.showPasswordDialog = false;
    },

    // 执行注册操作
    register() {
      if (!this.canRegister) return;

      if (this.registerCode !== this.storeVerificationCode) {
        this.$toast({
          message: '验证码错误',
          position: 'top',
        });
        return;
      }

      const users = JSON.parse(localStorage.getItem('users') || '[]');
      const existingUser = users.find(u => u.phoneNumber === this.registerPhone);
      if (existingUser) {
        this.$toast({
          message: '该手机号已注册',
          position: 'top',
        });
        return;
      }

      const defaultNickname = this.getDefaultNickname(this.registerPhone);
      const newUser = {
        phoneNumber: this.registerPhone,
        password: this.registerPassword,
        nickname: defaultNickname
      };
      users.push(newUser);
      localStorage.setItem('users', JSON.stringify(users));

      localStorage.setItem('isLoggedIn', 'true');
      localStorage.setItem('currentPhoneNumber', this.registerPhone);
      this.$toast({
        message: '注册成功',
        position: 'top',
      });
      this.hide();
      this.CLEAR_VERIFICATION_CODE();
      this.handleLoginSuccess();
    },

    // 根据手机号生成默认昵称
    getDefaultNickname(phoneNumber) {
      const lastFour = phoneNumber.slice(-4);
      return `用户${lastFour}`;
    },

    // 处理登录成功后的逻辑
    handleLoginSuccess() {
      // 触发登录成功事件，让 My.vue 更新状态
      this.$root.$emit('loginSuccess');

      // 如果不在"我的"页面，则跳转到首页
      if (this.currentRoutePath !== '/my') {
        this.$router.push('/');
      }
    }
  }
}
</script>

<style scoped lang="less">
@import url('../assets/login-input-icon/iconfont.css');

.login-register-overlay {
  width: 100vw;
  height: 100vh;
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  transform: translateY(100%);
  transition: transform 0.3s ease;

  &.slide-in {
    transform: translateY(0);
  }

  &.slide-out {
    transform: translateX(100%);
    transition: transform 0.3s ease;
  }
}

.login-module {
  width: 100vw;
  height: 100vh;
  background-color: #fff;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  transform: translateY(100%);
  transition: transform 0.3s ease;

  .close {
    position: absolute;
    top: 20px;
    left: 20px;
    font-size: 12px;
    cursor: pointer;
    z-index: 1;
    color: #fff;
  }

  .login-img {
    margin-bottom: 10px;

    img {
      width: 100%;
      display: block;
      height: auto;
    }
  }

  .login-title {
    display: flex;
    flex-direction: column;
    padding: 0 5vw;
    box-sizing: border-box;
    margin-top: 20px;
    margin-bottom: 30px;

    span:nth-child(1) {
      font-size: 10px;
      line-height: 14px;
      margin-bottom: 5px;
    }

    span:nth-child(2) {
      font-size: 8px;
      color: #cdcdcd;
    }
  }

  .login-input {
    padding: 0 5vw;
    box-sizing: border-box;

    input {
      width: 80%;
      border: none;
      outline: none;
      font-size: 10px;
    }

    .phone-number {
      display: flex;
      align-items: center;
      width: 100%;
      padding: 5px 0;
      border-bottom: 1px solid #cdcdcd;
      margin-bottom: 10px;

      >.login-iconfont {
        font-size: 18px;
      }
    }

    .verification-code {
      display: flex;
      align-items: center;
      width: 100%;
      padding: 5px 0;
      border-bottom: 1px solid #cdcdcd;
      position: relative;

      .send-code {
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 10px;
        cursor: pointer;
        color: #000;
        transition: color 0.3s ease;

        &.disabled {
          color: #999;
          cursor: not-allowed;
        }
      }

      .error-tip {
        position: absolute;
        top: -20px;
        left: 0;
        font-size: 10px;
        color: #ff4444;
      }

      .show-password {
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
      }
    }
  }

  >.agreement-module {
    margin-top: 35px;
  }

  .login-btn {
    margin-left: 5vw;
    width: 90vw;
    border: none;
    height: 4vh;
    border-radius: 8px;
    margin-top: 15px;
    margin-bottom: 10px;
    background-color: #aaa;
    color: #fff;
    font-size: 10px;
    transition: background-color 0.3s ease;
    cursor: pointer;

    &:disabled {
      cursor: not-allowed;
      opacity: 0.6;
    }
  }

  .login-options {
    padding: 0 6vw;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 10px;
    margin-bottom: 40px;
  }
}

.register-module {
  width: 100vw;
  height: 100vh;
  background-color: #fff;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  transform: translateY(100%);
  transition: transform 0.3s ease;

  .close {
    position: absolute;
    top: 20px;
    left: 20px;
    font-size: 12px;
    cursor: pointer;
    z-index: 1;
    color: #fff;
  }

  .register-img {
    img {
      width: 100%;
      display: block;
      height: auto;
    }
  }

  .register-title {
    display: flex;
    flex-direction: column;
    padding: 0 5vw;
    box-sizing: border-box;
    margin-top: 20px;
    margin-bottom: 30px;

    span:nth-child(1) {
      font-size: 10px;
      line-height: 14px;
      margin-bottom: 5px;
    }

    span:nth-child(2) {
      font-size: 8px;
      color: #cdcdcd;
    }
  }

  .register-input {
    margin-top: 20px;
    padding: 0 5vw;
    box-sizing: border-box;

    .phone-number,
    .verification-code,
    .password-input {
      display: flex;
      align-items: center;
      width: 100%;
      padding: 5px 0;
      border-bottom: 1px solid #cdcdcd;
      position: relative;
      margin-bottom: 15px;

      input {
        width: 100%;
        border: none;
        outline: none;
        padding: 5px 10px;
        font-size: 12px;
      }

      .send-code {
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 10px;
        cursor: pointer;
        color: #000;
        transition: color 0.3s ease;

        &.disabled {
          color: #999;
          cursor: not-allowed;
        }
      }

      .error-tip {
        position: absolute;
        top: -20px;
        left: 0;
        font-size: 10px;
        color: #ff4444;
      }

      .show-password {
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
      }
    }
  }

  .register-btn {
    margin-left: 5vw;
    width: 90vw;
    border: none;
    height: 4vh;
    border-radius: 8px;
    margin-top: 15px;
    margin-bottom: 10px;
    background-color: #aaa;
    color: #fff;
    font-size: 10px;
    transition: background-color 0.3s ease;
    cursor: pointer;

    &:disabled {
      cursor: not-allowed;
      opacity: 0.6;
    }
  }
}

.agreement-module {
  width: 100%;
  font-size: 8px;
  color: #cdcdcd;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 2px;

  .circle {
    height: 12px;
    aspect-ratio: 1/1;
    border: 1px solid #cdcdcd;
    border-radius: 50%;
    margin-right: 2px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    cursor: pointer;
    transition: all 0.3s ease;

    &.active {
      background-color: #000;
      border-color: #000;
    }
  }

  span {
    color: #000;
  }
}

.password-dialog-content {
  padding: 20px 0;
}

.password-input-wrapper {
  position: relative;
  width: 100%;
}

.password-dialog-input {
  width: 100%;
  padding: 10px 35px 10px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 14px;
  outline: none;
}

.password-input-wrapper .login-iconfont {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  font-size: 18px;
  color: #999;
  z-index: 1;
  display: inline-block;
  width: 18px;
  height: 18px;
  text-align: center;
  line-height: 18px;
}
</style>
